#-*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import Warning
from odoo.tools.translate import _
import odoo.addons.decimal_precision as dp
from datetime import datetime

class TransientImportproduct_attribute(models.Model):
    _name = 'import.product_attribute.transient'
    _rec_name = ''
    _description = 'import product_attribute'

    created_by = fields.Many2one('res.users', u'创建人', default=lambda self: self.env.user)

    product_attribute_line_ids = fields.One2many('import.product_attribute.line.transient', 'template_product_attribute_id', u'明细', copy=True)

    name = fields.Char(u'名称')
    category = fields.Char(u'分类')
    uom = fields.Char(u'主单位')
    po_uom = fields.Char(u'采购单位')
    note = fields.Char(u'导入说明')
    can_po = fields.Boolean(u'可采购')
    can_so = fields.Boolean(u'可销售')
    can_exp = fields.Boolean(u'可报销')

    error_message = fields.Char(u'验证详情')
    can_import = fields.Boolean(u'验证结果')
    done_import = fields.Boolean(u'已导入')
    not_existed = fields.Boolean(u'产品不存在')

    computed_template_id = fields.Many2one('product.template', u'检验产品')
    computed_category_id = fields.Many2one('product.category', u'检验分类')
    computed_type = fields.Selection([
        ('consu', _(u'可消耗')),
        ('product', _(u'可库存产品')),
        ('service', _(u'服务'))], string=u'产品类型', default='product', required=True)
    computed_uom= fields.Many2one('product.uom', u'检验主单位')
    computed_po_uom= fields.Many2one('product.uom', u'检验采购单位')
    
    


    def prepare_import(self,att,att_vals):
        if self.can_import:
            return {'product_tmpl_id': self.computed_template_id.id,
                    'attribute_id':att.id,
                    'value_ids': [(6, 0, att_vals)]
            }
        else:
            return None
    @api.one
    def verify(self):
        self.error_message = u''
        self.not_existed = True
        self.can_import = False

        products = None
        if self.name:
            # products = self.env['product.template'].search([('name','=',self.name)])
            categ = self.env['product.category'].search([('name', '=', self.category)])
            uom = self.env['product.uom'].search([('name', '=', self.uom)])
            po_uom = self.env['product.uom'].search([('name', '=', self.po_uom)])
        if categ and uom and po_uom and not products:
            self.not_existed = False
            self.computed_category_id = categ[0]
            self.computed_uom = uom[0]
            self.computed_po_uom = po_uom[0]

            products = self.env['product.template'].create({
                'name': self.name,
                'categ_id': self.computed_category_id.id,
                'uom_id': self.computed_uom.id,
                'uom_po_id': self.computed_po_uom.id,
                'computed_type': self.computed_type,
                'purchase_ok': self.can_po,
                'sale_ok': self.can_so,
                'can_be_expensed': self.can_exp,
            })
        if products and categ and uom and po_uom:
            self.computed_template_id = products[0]

            attrs=[]
            for at_line in products[0].attribute_line_ids:
                attrs.append(at_line.attribute_id)

            i = 0
            for line in self.product_attribute_line_ids:
                line.error_message = u''
                computed_attribute = None
                computed_attribute_value = None
                i+=1
                if line.attribute:
                    computed_attribute = self.env['product.attribute'].search([('name','=',line.attribute)])
                if line.attribute and line.attribute_value:

                    computed_attribute_value = self.env['product.attribute.value'].search([('name','=',line.attribute_value),('attribute_id','=',computed_attribute[0].id)])
                if computed_attribute and computed_attribute_value:
                    line.computed_attribute=computed_attribute[0]
                    line.computed_attribute_value=computed_attribute_value[0]
                    if attrs.count(computed_attribute)>0:
                        self.can_import = False
                        line.error_message += u'【第' + str(i) + u'行，' + u'产品已有该属性，不能导入!】'
                if not computed_attribute:
                    self.can_import = False
                    line.error_message += u'【第'+str(i)+u'行，'+u'系统没有该属性!】'
                if not computed_attribute_value:
                    self.can_import = False
                    line.error_message += u'【第'+str(i)+u'行，'+u'系统没有该属性值!】'
            if all([l.computed_attribute and not l.error_message for l in self.product_attribute_line_ids]):
                self.can_import = True
            else:
                self.can_import = False
                self.error_message += u'明细有问题,请检查'
        else:
            self.not_existed=True
            self.error_message += u'产品中有必填信息缺失！'
            self.can_import = False

    @api.one
    def start_import(self):
        for i in self:
            if i.can_import and not i.not_existed:
                atts=[]
                for line in self.product_attribute_line_ids:
                    if not line.computed_attribute in atts:
                        atts.append(line.computed_attribute)
                for att in atts:

                    att_vals=[]
                    for line in self.product_attribute_line_ids:
                        if line.computed_attribute==att and not line.computed_attribute_value.id in att_vals:
                            att_vals.append(line.computed_attribute_value.id)
                    res = self.env['product.attribute.line'].create(i.prepare_import(att,att_vals))
                i.computed_template_id.uom_id=i.computed_uom and i.computed_uom.id or i.computed_template_id.uom_id.id
                i.computed_template_id.uom_po_id=i.computed_po_uom and i.computed_po_uom.id or i.computed_template_id.uom_po_id.id
                i.computed_template_id.categ_id=i.computed_category_id and i.computed_category_id.id or i.computed_template_id.categ_id.id
                i.computed_template_id.computed_type=i.computed_type
                i.computed_template_id.purchase_ok=i.can_po
                i.computed_template_id.sale_ok=i.can_so
                # i.computed_template_id.sale_ok=i.can_exp
                i.computed_template_id.create_variant_ids()
                i.done_import = True

class TransientImportproduct_attributeLine(models.Model):
    _name = 'import.product_attribute.line.transient'
    _description = 'import product_attribute line'

    template_product_attribute_id = fields.Many2one('import.product_attribute.transient', u'表单')

    attribute = fields.Char(u'属性')
    attribute_value = fields.Char(u'属性值')

    error_message = fields.Char(u'验证详情')

    computed_attribute = fields.Many2one('product.attribute', u'验证属性')
    computed_attribute_value = fields.Many2one('product.attribute.value', u'验证属性值')

    note = fields.Char(u'导入说明')


